/*
 * Copyright (c) 2011. c.mueller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package de.altitude.cimuelle.commandhandles;

import de.altitude.cimuelle.Config;
import de.altitude.cimuelle.MessageBundle;
import de.altitude.cimuelle.coop.CoopDataHandler;
import de.altitude.cimuelle.coop.CoopGame;
import de.altitude.cimuelle.utils.ServerUtils;
import de.altitude.cimuelle.utils.StringUtils;
import de.altitudecustomcommands.exceptions.ServerNotFoundException;
import de.altitudecustomcommands.playerHandler;
import de.altitudecustomcommands.serverInformations;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static de.altitude.cimuelle.utils.ServerOperations.sendServerMessage;

/**
 * Class description:
 * processes objective start / stop commands
 * User: cybernaut
 * Date: 07.10.11
 * Time: 23:02
 */
public class TypeObjectiveHandler {
    private static final Logger LOGGER = Logger.getLogger("TypeObjectiveHandler");

    private final playerHandler playerList;
    private final serverInformations server;

    public TypeObjectiveHandler(playerHandler playerList, serverInformations server) {
        this.playerList = playerList;
        this.server = server;
    }

    public void typeGameStart(String port) {
        if (Config.getInstance().isCoopRankingActiveByPort(port)) {
            if (ServerUtils.checkCountingRequirementsForCoop(port, server, playerList, null)) {
                try {
                    CoopGame coopGame = CoopDataHandler.newCoopGame(port, server.getServerByPort(port));
                    if (ServerUtils.checkCountingRequirementsForCoop(port, server, playerList, coopGame)) {
                        // coop-game will be saved from method itself later
                    } else {
                        // error within checking method
                    }
                } catch (ServerNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void typeGameStop(String port, Map json) {
        // {"port":28378,"time":206986139,"winningTeam":4,"timeSeconds":167.9,"type":"objectiveGameEnd"}
        if (Config.getInstance().isCoopRankingActiveByPort(port)) {
            LOGGER.debug(port + ": EndObjective received.");
            int winningTeam = ((Number) json.get("winningTeam")).intValue();
            double timeSeconds = ((Number) json.get("timeSeconds")).doubleValue();
            CoopGame coopGame = CoopDataHandler.getActiveGame(port);
            if (coopGame != null && coopGame.getDatabaseId() > -1) {
                LOGGER.info(port + ":Coopgame " + coopGame.getDatabaseId() + " ended with team " + winningTeam + " won in " + timeSeconds + " seconds.");
                CoopDataHandler.endCoopGame(port, playerList, winningTeam, timeSeconds);

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("RANK", String.valueOf(coopGame.getRank()));
                map.put("DURATION", String.valueOf(coopGame.getDuration()));
                map.put("ID", String.valueOf(coopGame.getDatabaseId()));

                sendServerMessage(port, MessageBundle.getString("scoopEnd1", map));
                if (coopGame.isBaseDestroyed()) {
                    sendServerMessage(port, MessageBundle.getString("scoopEnd2BaseDestroyed", map));
                    sendServerMessage(port, MessageBundle.getString("scoopEnd3Rank", map));
                    List<CoopGame> coopGameRanks = CoopDataHandler.getGameRanksByGame(coopGame);
                    sendServerMessage(port, StringUtils.buildCoopRankString(coopGameRanks));
                } else {
                    sendServerMessage(port, MessageBundle.getString("scoopEnd4BaseNotDestroyed", map));
                }
            }
        }
    }
}
